package com.ikingtech.platform.service.system.organization.service;

import com.ikingtech.framework.sdk.context.security.Me;
import com.ikingtech.framework.sdk.organization.api.OrgUserApi;
import com.ikingtech.framework.sdk.organization.model.OrganizationDTO;
import com.ikingtech.framework.sdk.organization.model.OrganizationManagerDTO;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.organization.entity.OrganizationDO;
import lombok.RequiredArgsConstructor;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class ModelConverter {

    private final OrgUserApi orgUserApi;

    private final OrganizationService service;

    public List<OrganizationDTO> modelConvert(List<OrganizationDO> entities) {
        List<OrganizationDO> subEntities = this.service.listSubByFullPaths(Tools.Coll.convertList(entities, OrganizationDO::getFullPath));
        Map<String, Integer> userCountMap = this.orgUserApi.getUserCount(Tools.Coll.convertList(subEntities, OrganizationDO::getId));
        List<OrganizationManagerDTO> managers = this.orgUserApi.loadManagers(Tools.Coll.convertList(entities, OrganizationDO::getManagerId));
        Map<String, OrganizationManagerDTO> managerMap = Tools.Coll.convertMap(managers, OrganizationManagerDTO::getUserId, manager -> manager);
        return Tools.Coll.convertList(entities, entity -> {
            List<String> subEntityIds = Tools.Coll.flatMap(
                    Tools.Coll.filter(subEntities, subEntity -> subEntity.getFullPath().startsWith(entity.getFullPath())),
                    subEntity -> Tools.Str.split(subEntity.getFullPath().substring(subEntity.getFullPath().indexOf(subEntity.getId())), "@"),
                    Collection::stream
            );
            return this.modelConvert(entity, managerMap.get(entity.getManagerId()), Tools.Coll.mapFilter(userCountMap, entry -> subEntityIds.contains(entry.getKey())));
        });
    }

    public OrganizationDTO modelConvert(OrganizationDO entity,
                                OrganizationManagerDTO manager,
                                Map<String, Integer> userCountMap) {
        OrganizationDTO organization = Tools.Bean.copy(entity, OrganizationDTO.class);
        organization.setManager(manager);
        organization.setUserCount(Tools.Coll.mapSum(userCountMap));
        organization.setInDataScope(Tools.Coll.isBlank(Me.dataScope()) || Me.dataScope().contains(organization.getId()));
        return organization;
    }
}
